package com.sam.admin.config;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

@Configuration
public class HttpClientConfig {

    @Value("${iukos.maxTotal}")
    private int maxTotal;
    @Value("${iukos.maxPerRoute}")
    private int maxPerRoute;
    @Value("${iukos.connectTimeOut}")
    private int connectTimeOut;
    @Value("${iukos.connectionRequestTimeOut}")
    private int connectionRequestTimeOut;
    @Value("${iukos.socketTimeOut}")
    private int socketTimeOut;

    @Bean
    public HttpClientUtil getHttpClientUtil(){
        SSLContextBuilder builder = new SSLContextBuilder();
        try {
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        SSLConnectionSocketFactory sslsf = null;
        try {
            sslsf = new SSLConnectionSocketFactory(builder.build());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        // 配置同时支持 HTTP 和 HTPPS
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
        // 初始化连接管理器
        PoolingHttpClientConnectionManager poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        poolConnManager.setMaxTotal(this.maxTotal);// 同时最多连接数 //todo 可配置
        poolConnManager.setDefaultMaxPerRoute(this.maxPerRoute);// 设置最大路由
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(this.connectTimeOut)
                .setConnectionRequestTimeout(this.connectionRequestTimeOut)
                .setSocketTimeout(this.socketTimeOut)
                .setRedirectsEnabled(true).build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(poolConnManager)
                .setDefaultRequestConfig(requestConfig)
//                .evictExpiredConnections()
//                .evictIdleConnections(30, TimeUnit.SECONDS)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2,false)).build();
        return new HttpClientUtil(httpClient);
    }

}
